package com.han.gateway.filter;

import com.han.gateway.config.IpsConfig;
import lombok.AllArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@AllArgsConstructor
public class ValidateIpFilter implements GlobalFilter {

    private final IpsConfig ipsConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        Mono<Void> failMono = Mono.defer(() -> {
            response.setStatusCode(HttpStatus.FORBIDDEN);
            byte[] bytes = "黑白名单校验不通过".getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(buffer));
        });

        InetSocketAddress remoteAddress = request.getRemoteAddress();
        if (remoteAddress == null) {
            return failMono;
        }
        String hostName = remoteAddress.getHostName();

        List<String> whites = ipsConfig.getWhites();
        List<String> blacks = ipsConfig.getBlacks();

        if (!CollectionUtils.isEmpty(whites) && !whites.contains(hostName)) {
            return failMono;
        }

        if (CollectionUtils.isEmpty(whites) && !CollectionUtils.isEmpty(blacks) && blacks.contains(hostName)) {
            return failMono;
        }

        return chain.filter(exchange);
    }
}
